package com.wxg.druid;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

public class DruidDemo {

	public static void main(String[] args) throws Exception {
		DruidDemo dd = new DruidDemo();
//		dd.test01();
		dd.sampleUseDruid();
	}
	
	/**
	 * 根据提供的"config"加载properties配置文件
	 * 
	 * @param config
	 * @return
	 * @throws IOException
	 */
	public Properties loadProp(String config){
		Properties prop = new Properties();
		InputStream is = getClass().getClassLoader().getResourceAsStream(config);
		try {
			try {
				prop.load(is);
			} finally {
				is.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return prop;
	}
	
	public void sampleUseDruid(){
		DruidDataSource dds = new DruidDataSource();
		dds.addConnectionProperty("username", "root");
		dds.addConnectionProperty("password", "root");
		dds.addConnectionProperty("jdbcUrl", "jdbc:mysql://127.0.0.1:3306/openapi");
//		driverClass
//		driverClass
//		dds.addConnectionProperty("driverClass", "com.mysql.jdbc.Driver");
		try {
			DruidPooledConnection druidpool = dds.getConnection();
			Connection conn = druidpool.getConnection();
			Statement stmt = conn.createStatement();
			String sql = "SELECT COUNT(1) FROM api_app";
			ResultSet rs = stmt.executeQuery(sql);
			System.out.println("======");
			while(rs.next()){
				System.out.println(rs.getInt(1));
			}
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			dds.close();
		}
	}
	
	
	
	public void test03(){
		Properties prop = loadProp("druid/config01.properties");
		DruidDataSource dds = new DruidDataSource();
		dds.configFromPropety(prop);
		
	}
	
	public void test02(){
		Properties prop = loadProp("druid/config01.properties");
		try {
			DataSource ds = DruidDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void test01() throws Exception{
		String config = "druid/config01.properties";
		Properties prop = loadProp(config);
		prop.list(System.out);
	}
}
